import csv

def generate_binary(row):
    # 创建48位全0列表
    bits = ['0'] * 48
    # 处理每个单元格
    for cell in row:
        if cell.startswith('c'):
            # 提取数字部分
            idx = int(cell[1:])
            if idx < 48:
                bits[47 - idx] = '1'  # 右边为低位，左边为高位
    return ''.join(bits)

def process_csv(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', newline='', encoding='utf-8') as outfile:
        reader = csv.reader(infile)
        writer = csv.writer(outfile)
        
        for row in reader:
            # 过滤空值并生成二进制字符串
            cleaned_row = [cell for cell in row if cell.strip()]
            binary_str = generate_binary(cleaned_row)
            # 写入原始数据 + 二进制字符串
            writer.writerow(row + [binary_str])



process_csv('control_signal.csv', 'output.csv')
with open('output.csv', 'r', encoding='utf-8') as infile, open('CM_ROM.coe', 'w', newline='', encoding='utf-8') as outfile_coe:
    outfile_coe.write("MEMORY_INITIALIZATION_RADIX=2;\n")
    outfile_coe.write("MEMORY_INITIALIZATION_VECTOR=\n")
    reader = csv.reader(infile)
    rows = list(reader)
    for i, row in enumerate(rows):
        outfile_coe.write(row[-1])
        if i < len(rows) - 1:
            outfile_coe.write(",\n")
        else:
            outfile_coe.write(";\n")


